package mySpringMVC;
import myJava.DBConn;
import myJava.Employee;
import myJava.Modify;
import myJava.News;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/utf8")
public class HelloWorld{

    @RequestMapping("/helloWorld")
    public String showNews(News news){
        System.out.println("Hello World!");
        System.out.println(news);
//        String exec = new ActionEnter(request, rootPath).exec();
        return "success";
    }

    @RequestMapping("/back")
    public ModelAndView back(){
        return getAllData();
    }

    @RequestMapping("/login")
    public ModelAndView checkLogin(Employee employee){
        //判断用户账号和密码
        Boolean isTrue = DBConn.check(employee);
        if (isTrue)
        {
            return getAllData();
        }
        else
            return new ModelAndView("loginAgain");//在视图解析器中添加前缀和后缀
    }

    @RequestMapping("/Info")
    public ModelAndView newsInfo(@RequestParam("id") int id){
        News news =DBConn.getNewsById(id);
        ModelAndView modelAndView = new ModelAndView("info");
        modelAndView.addObject("one",news);
        return modelAndView;
    }

    @RequestMapping(value = "/AddNews")
    public ModelAndView addNews(@RequestParam("title") String title, @RequestParam("author") String author,
                                @RequestParam("content") String content){

        News news = new News();
        news.setTitle(title);
        news.setAuthor(author);
        news.setContent(content);
        news.setTime(new Date());

        if (!Modify.modify){
            //向数据库写入数据
            DBConn.insertNews(news);
        }
        else{
            news.setId(Modify.modifyId);
            DBConn.upDataNewsById(news);
            //重置Modify为默认状态
            Modify.modify = false;
            Modify.modifyId = -1;
        }
        return getAllData();
    }

    @RequestMapping("/delete")
    public ModelAndView deleteNews(@RequestParam("id") int id){
        DBConn.deleteNews(id);
        return getAllData();
    }

    @RequestMapping("/upData")
    public ModelAndView upDataMethod(@RequestParam("id") int id){
        //数据库获取待修改的新闻信息
        News news = DBConn.getNewsById(id);
        //将数据发送至新闻编辑页面进行填充
        ModelAndView modelAndView = new ModelAndView("addNews");
        modelAndView.addObject("updata",news);
        //设置修改操作的标识
        Modify.modify = true;
        //设置修改的新闻id
        Modify.modifyId = id;
        return modelAndView;
    }


    public ModelAndView getAllData(){
        List<News> list = DBConn.getAllNews();
        //创建返回数据的ModelAndView
        ModelAndView modelAndView = new ModelAndView("newsPublish");
        modelAndView.addObject("list",list);
        return modelAndView;
    }
}
